from django.http import HttpResponse
from django.shortcuts import render, redirect
from django import forms

from app02 import models
from app02.utils.bootstrap import BootstrapForm
from app02.utils.encrypte import md5
from app02.utils.code import check_code


class LoginForm(BootstrapForm):
    username = forms.CharField(
        label="用户名",
        widget=forms.TextInput,
        required=True,
    )
    password = forms.CharField(
        label="密码",
        widget=forms.PasswordInput(render_value=True),
        required=True,
    )

    def clean_password(self):
        pwd = self.cleaned_data.get("password")
        return md5(pwd)


def login(request):
    """ 用户登录 """
    if request.method == 'GET':
        form = LoginForm()
        return render(request, "login.html", {'form': form})

    form = LoginForm(data=request.POST)
    if form.is_valid():
        admin_object = models.Admin.objects.filter(**form.cleaned_data).first()
        if not admin_object:
            form.add_error("password", "用户名或密码错误")
            return render(request, 'login.html', {'form': form})

    request.session['info'] = {'id': admin_object.id, 'name': admin_object.username}
    return redirect("/admin/list/")


from io import BytesIO


# def image_code(request):
#     """ 生产图形验证码 """
#     img, code_string = check_code()
#
#     request.session['image_code'] = code_string
#     request.session.set_expiry(60)
#
#     stream = BytesIO()
#     img.save(stream, 'png')
#     return HttpResponse(stream.getvalue())


def logout(request):
    """ 注销 """
    request.session.clear()
    return redirect("/login/")